<template>
  <el-dialog
    v-model="dialogVisible"
    title="创建新课程"
    :before-close="handleDialogClose"
    width="65%"
  >
    <el-form
      ref="courseFormRef"
      :model="courseForm"
      :rules="rules"
      label-width="80px"
      class="course-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="课程ID" prop="id">
            <el-input
              v-model="courseForm.id"
              placeholder="请输入课程ID"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学期" prop="semester">
            <el-select
              v-model="courseForm.semester"
              placeholder="请选择学期"
              class="w-full"
            >
              <el-option
                v-for="item in semesterOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="课程名称" prop="name">
        <el-input
          v-model="courseForm.name"
          placeholder="请输入课程名称"
        />
      </el-form-item>

      <el-form-item label="课程描述" prop="description">
        <el-input
          v-model="courseForm.description"
          type="textarea"
          :rows="4"
          placeholder="请输入课程描述"
        />
      </el-form-item>

      <el-form-item label="课程大纲" prop="syllabus">
        <el-input
          v-model="courseForm.syllabus"
          type="textarea"
          :rows="4"
          placeholder="请输入课程大纲"
        />
      </el-form-item>

      <el-form-item label="课程时间" prop="time">
        <CourseTimeSelector
          v-model="courseForm.time"
          @update:modelValue="handleTimeUpdate"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确 定
        </el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import CourseTimeSelector from './CourseTimeSelector.vue';

export default {
  name: 'CreateCourseDialog',
  components: {
    CourseTimeSelector
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue', 'course-created'],
  setup(props, { emit }) {
    const courseFormRef = ref(null)
    const loading = ref(false)

    // 计算当前学年学期
    const getCurrentSemester = () => {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth() + 1
      return month >= 2 && month <= 7 ? `${year}-2000` : `${year}-1000`
    }

    // 学期选项
    const semesterOptions = computed(() => {
      const currentYear = new Date().getFullYear()
      return [
        { label: `${currentYear}-${currentYear + 1}学年第一学期`, value: `${currentYear}-1000` },
        { label: `${currentYear}-${currentYear + 1}学年第二学期`, value: `${currentYear}-2000` }
      ]
    })

    // 表单数据
    const courseForm = reactive({
      id: '',
      semester: getCurrentSemester(),
      name: '',
      description: '',
      syllabus: '',
      time: '{}'
    })

    // 表单验证规则
    const rules = {
      id: [
        { required: true, message: '请输入课程ID', trigger: 'blur' },
      ],
      semester: [
        { required: true, message: '请选择学期', trigger: 'change' }
      ],
      name: [
        { required: true, message: '请输入课程名称', trigger: 'blur' },
      ],
      description: [
        { required: true, message: '请输入课程描述', trigger: 'blur' }
      ],
      syllabus: [
        { required: true, message: '请输入课程大纲', trigger: 'blur' }
      ]
    }

    // 计算对话框可见性
    const dialogVisible = computed({
      get: () => props.modelValue,
      set: (value) => emit('update:modelValue', value)
    })

    // 处理时间更新
    const handleTimeUpdate = (value) => {
      courseForm.time = value
    }

    // 处理表单提交
    const handleSubmit = async () => {
      if (!courseFormRef.value) return

      await courseFormRef.value.validate(async (valid, fields) => {
        if (valid) {
          loading.value = true
          try {
            const response = await fetch('/backend/api/course/courses/create/', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              credentials: 'include',
              body: JSON.stringify(courseForm)
            })

            if (!response.ok) {
              throw new Error('创建课程失败')
            }

            const data = await response.json()
            ElMessage.success('创建课程成功')
            emit('course-created', data)
            handleCancel()
          } catch (error) {
            console.error('创建课程失败:', error)
            ElMessage.error('创建课程失败: ' + error.message)
          } finally {
            loading.value = false
          }
        } else {
          console.error('表单验证失败:', fields)
        }
      })
    }

    // 处理取消
    const handleCancel = () => {
  dialogVisible.value = false
  if (courseFormRef.value) {
    courseFormRef.value.resetFields()
  }
}

    // 处理对话框关闭
    const handleDialogClose = (done) => {
      ElMessage.warning('操作取消')
      handleCancel()
      done()
    }

    return {
      courseFormRef,
      courseForm,
      rules,
      loading,
      dialogVisible,
      semesterOptions,
      handleTimeUpdate,
      handleSubmit,
      handleCancel,
      handleDialogClose
    }
  }
}
</script>

<style scoped>
.course-form {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: bold;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

:deep(.el-select) {
  width: 100%;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .el-dialog {
    width: 90% !important;
  }

  :deep(.el-form-item__label) {
    float: none;
    display: block;
    text-align: left;
    padding: 0 0 10px;
  }
}
</style>